import java.io.*;

import javassist.*;
import javassist.bytecode.*;


public class CodeModifier {

    public static void main(String[] args) throws Exception {

        Options options = Options.createOptions(args);


        CtClass ctClazz = options.getClassPool().get(getClassName(options.getSrcFileName()));
        ctClazz.stopPruning(true);

        ClassFile classFile = ctClazz.getClassFile();


        for (CtMethod ctMethod : ctClazz.getDeclaredMethods()) {
            NotNullInstrumenter notNullInstrumenter = new NotNullInstrumenter(options, classFile.getConstPool());
            notNullInstrumenter.insrumentMethod(ctMethod);
        }


        ctClazz.defrost();
        writeClassFile(ctClazz, options.getDestFileName());
    }

    private static void writeClassFile(CtClass ctClazz, String destFileName) throws IOException {
        String className = getClassName(destFileName);
        ClassFile cf = ctClazz.getClassFile();
        cf.setName(className);
        DataOutputStream s = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(destFileName)));
        try {
            cf.write(s);
        }
        finally {
            s.close();
        }
    }

    private static String getClassName(String fileName) {
        File file = new File(fileName);
        String className = file.getName();
        if (className.endsWith(".class")) {
            className = className.substring(0, className.length() - 6);
        }
        return className;
    }


}
